package com.example.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ImageChecker {
    private static final Map<String, String> fileTypeMap = new HashMap<>();
    static {
        fileTypeMap.put("FFD8FF", "jpg");
        fileTypeMap.put("89504E47", "png");
        fileTypeMap.put("47494638", "gif");
        fileTypeMap.put("424D", "bmp");
        fileTypeMap.put("49492A00", "tiff");
        fileTypeMap.put("4D4D002A", "tiff");
    }

    public static boolean isImageFile(MultipartFile file) throws IOException {
        // 检查文件扩展名
        String[] imageExtensions = {"jpg", "jpeg", "png", "gif", "bmp", "tiff"};
        String fileName = file.getOriginalFilename().toLowerCase();
        for (String extension : imageExtensions) {
            if (fileName.endsWith("." + extension)) {
                // 检查文件头
                byte[] bytes = file.getBytes();
                if (bytes.length < 8) {
                    return false;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < 8; i++) {
                    sb.append(String.format("%02X", bytes[i]));
                }
                String fileHeader = sb.toString();
                for (String key : fileTypeMap.keySet()) {
                    if (fileHeader.startsWith(key)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
